package com.xgure.service.impl;

import com.xgure.constant.MessageConstant;
import com.xgure.dto.ShopAddDTO;
import com.xgure.dto.ShopUpdateDTO;
import com.xgure.enumerator.RoleEnum;
import com.xgure.excption.DataNotEnoughException;
import com.xgure.excption.InvalidOperationException;
import com.xgure.mapper.EmployeeMapper;
import com.xgure.mapper.ShopMapper;
import com.xgure.pojo.Shop;
import com.xgure.properties.UploadProperties;
import com.xgure.service.ShopService;
import com.xgure.utils.BaseContextUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
public class ShopServiceImpl implements ShopService {

    private static final Logger log = LoggerFactory.getLogger(ShopServiceImpl.class);
    @Resource
    private ShopMapper shopMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private UploadProperties uploadProperties;

    /**
     * 添加新的店铺
     *
     */
    @Transactional
    @Override
    public void addNewShop(ShopAddDTO shopAddDTO) {
        // 判断传入的数据是否合法
        if (shopAddDTO.getShopName() == null || shopAddDTO.getShopName().trim().isEmpty()) {
            throw new DataNotEnoughException(MessageConstant.NEED_SHOP_NAME);
        }
        if (shopAddDTO.getContactPhone() == null) {
            throw new DataNotEnoughException(MessageConstant.NEED_PHONE_NUMBER);
        }
        // 封装插入的数据
        Shop shop = new Shop();
        BeanUtils.copyProperties(shopAddDTO, shop);
        // 创建店铺后默认有一个员工
        shop.setEmployeeCount(1);
        // 插入数据SQL
        shopMapper.add(shop);
        // 员工表中记录当前用户的店铺id并且将其身份设置成老板
        employeeMapper.setShopInfo(BaseContextUtil.getCurrentUserId(), shop.getId(), RoleEnum.ADMIN);
    }

    /**
     * 获取店铺信息
     *
     */
    @Override
    public Shop getShopInfo(String shopId) {
        // 获取当前登录用户的店铺id
        if (shopId == null || shopId.trim().isEmpty()) {
            throw new InvalidOperationException(MessageConstant.SHOP_NOT_FOUND);
        }
        // 根据店铺id查询店铺信息
        return shopMapper.getById(Long.parseLong(shopId));
    }

    /**
     * 添加店铺头像
     *
     */
    @Override
    public void addAvatar(MultipartFile file) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String fileName ;

        // TODO 完成上传头像的开发
    }

    /**
     * 更新店铺信息并返回更新后的信息
     *
     */
    @Override
    public Shop update(ShopUpdateDTO shopUpdateDTO) {
        shopMapper.update(shopUpdateDTO);
        return shopMapper.getById(shopUpdateDTO.getId());
    }
}
